// Device/pages/Info/components/sleep-component/index.js
const app = getApp();
import { logger } from '@/utils/util'
import { customNavigate } from '@/utils/route'
import {
    fetchSleepData
} from '@/services/device'
const statucMappings = {
    '1': '不在床',
    '2': '在床'
}
const deviceStatus = {
    0: '离线',
    1: '在线'
}
Component({
    properties: {
        deviceInfo: {
            default: null,
            type: Object
        }
    },
    observers: {
        deviceInfo(value) {
            let {
                tianyu_sleep_info,
                zcstatus,
                device_imei
            } = value;
            zcstatus = zcstatus.map(item => {
                return {
                    ...item,
                    status: statucMappings[item.status]
                }
            })
            this.startEcgDataFlow(device_imei)
            const data = new Map([
                ['device_status', '联网状态'],
                ['signal_strength', '信号强度'],
            ]);
            let obj = {
                device_status: deviceStatus[value['device_status']],
                signal_strength: value['signal_strength'] || '--'
            }
            let result = [];
            for (let [key, value] of Object.entries(obj)) {
                result.push({
                    key: data.get(key),
                    value
                })
            }
            this.setData({
                deviceData: result,
                lastRecord: zcstatus?.[0] || null,
            })

        }
    },
    lifetimes: {
        detached() {
            clearInterval(this.data.intervalId)
            clearInterval(this.data.fetchTimerId)
        }
    },
    data: {
        staticPrefix: app.globalData.STATIC_PREFIX,
        heartrateData: [],
        breatheData: [],
        intervalId: null,
        fetchTimerId: null
    },
    methods: {
        onNavigate() {
            const {
                device_type,
                product_type,
                device_imei
            } = this.data.deviceInfo;
            const params = {
                device_type,
                product_type,
                device_imei
            }
            customNavigate({
                url: `/Device/pages/History/index`,
                params
            })
        },
        startEcgDataFlow(device_imei) {
            const fillInterval = 60; // 用 0 填充的间隔时间（毫秒）
            const fetchInterval = 0.1 * 60 * 1000; // 每隔 5 分钟调用接口

            // 定时用 0 填充数据
            const intervalId = setInterval(() => {
                this.setData({
                    heartrateData: [0],
                    breatheData: [0]
                });
            }, fillInterval);

            // 定时调用接口获取数据
            const fetchTimerId = setInterval(async () => {
                try {
                    const res = await fetchSleepData({
                        device_imei
                    });

                    // 如果接口返回数据，更新心跳数据
                    const heartrateData = Number(res.data.heart_rate);
                    const breatheData = Number(res.data.respiratory_rate);
                    if (!isNaN(heartrateData) && !isNaN(breatheData)) {
                        this.setData({
                            heartrateData: [heartrateData],
                            breatheData: [breatheData]
                        });
                    }
                } catch (error) {
                    logger.error('接口调用失败：', error);
                }
            }, fetchInterval);

            // 保存定时器 ID，便于清理
            this.setData({
                intervalId,
                fetchTimerId,
            });
        }
    }
})